package com.leetcode.p100;

import com.bean.TreeNode;
import com.utils.TreeUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 采用 广度优先遍历(层序遍历)
 */
public class Test199 {

    public List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        help(result, queue, 1);

        return result;
    }

    private void help(ArrayList<Integer> result, Queue<TreeNode> queue, int size) {
        if (size == 0) {
            return;
        }
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();

            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }

            if (i == size - 1) {
                result.add(node.val);
            }
        }

        help(result, queue, queue.size());
    }

    public static void main(String[] args) {
        TreeNode root = TreeUtils.buildTree();
        TreeUtils.showTree(root);

        Test199 test = new Test199();
        List result = test.rightSideView(root);
        System.out.println(result);
    }

}
